package com.idata.model.entity;

import com.alibaba.fastjson2.JSONObject;
import lombok.Data;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @File ResultObject.Java
 * @Modify Time      @Author    @Version    @Description
 * ------------      -------    --------    -----------
 * 2023/9/21         yd.j      1.0         None
 */
@Data
public class ResultObject {

    private String spaceName;
    private List<ResultData> data;
    private List<String> columns;
    private Errors errors;
    private String latencyInUs;
    private List<Object> result;


    @Data
    public static class ResultData {
        private List<String> meta;
        private List<String> row;
    }

    @Data
    public static class Errors {
        private int code;
    }

    /**
     * 将数据转成相应的类型
     */
    public void convert() {
        result = new ArrayList<>();
        for (ResultData datum : data) {
            List<String> meta = datum.getMeta();
            List<String> rows = datum.getRow();
            for (int i = 0; i < meta.size(); i++) {
                // 只有属性
                if (meta.get(i) == null) {
                    result.add(rows.get(i));
                    continue;
                }
                JSONObject jsonObject = new JSONObject();
                JSONObject metaData = JSONObject.parseObject(meta.get(i));
                Object to = null;
                if (metaData.get("type").equals("vertex")) {
                    jsonObject.putAll(metaData);
                    JSONObject jsonRow = JSONObject.parseObject(rows.get(i));
                    JSONObject jsonDemo = new JSONObject();
                    Set<String> strings = jsonRow.keySet();
                    String commonPrefix = "";
                    for (String string : strings) {
                        String[] split = string.split("\\.");
                        commonPrefix = split[0];
                        jsonDemo.put(split[1], jsonRow.get(string));
                    }
                    JSONObject jsonVertex = new JSONObject();
                    jsonVertex.put(commonPrefix, jsonDemo);
                    jsonObject.putAll(jsonVertex);
                    to = jsonObject.to(VertexEntity.class);
                    result.add(to);
                } else {
                    JSONObject id = (JSONObject) metaData.get("id");
                    String name = (String) id.get("name");
                    for (String key : id.keySet()) {
                        jsonObject.put(key, id.get(key));
                    }
                    JSONObject jsonRow = JSONObject.parseObject(rows.get(i));
                    JSONObject jsonEdge = new JSONObject();
                    jsonEdge.put(name, jsonRow);
                    jsonObject.putAll(jsonEdge);
                    to = jsonObject.to(EdgeEntity.class);
                }
                result.add(to);

            }
        }
    }

}
